<template>
  <div class="list-page">
    <el-card>
      <div class="list-h align-center">
        <el-button
          type="primary"
          @click="handleAdd"
          class="add-option"
          v-auth="`/projectsS/other--add`"
          >新增</el-button
        >
        <div class="list-h">
          <el-form
            :inline="true"
            :model="formInline"
            ref="formRef"
            class="demo-form-inline"
          >
            <el-form-item label="问题标题" prop="snapshotName">
              <el-input
                clearable
                class="width-custom120"
                v-model.trim="formInline.snapshotName"
                @change="handleSearch"
              ></el-input>
            </el-form-item>

            <el-form-item label="更新时间">
              <el-date-picker
                class="width-custom230"
                v-model="timeValue"
                type="daterange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                @change="handleChangeDate"
              />
            </el-form-item>
          </el-form>

          <div class="ml10">
            <el-button @click="handleReset">重置</el-button>
            <el-button
              type="primary"
              @click="handleSearch"
              v-auth="`/projectsS/other--query`"
              >查询</el-button
            >
          </div>
        </div>
      </div>

      <el-skeleton
        style="height: calc(100vh - 340px)"
        :rows="8"
        :loading="loading"
        animated
      >
      </el-skeleton>
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        v-loading="loading"
        v-show="!loading"
        :height="'calc(100vh - 340px)'"
        :header-cell-style="{
          background: '#F7F9FD',
          color: '#000',
          height: '48px',
          borderTop: '1px soild #E4E8F2'
        }"
      >
        <template #empty>
          <el-empty :image-size="150" description="暂无数据"></el-empty>
        </template>

        <el-table-column type="index" label="序号" width="80">
          <template v-slot="scope">
            <span>{{
              (pageState.pageNum - 1) * pageState.pageSize + scope.$index + 1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="snapshotName" label="问题标题">
        </el-table-column>
        <el-table-column prop="content" label="问题内容"> </el-table-column>
        <el-table-column prop="createTime" label="更新时间"> </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template #default="{ row }">
            <el-button
              type="text"
              size="small"
              @click="handleShowDetail(row)"
              v-auth="`/projectsS/other--detail`"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <re-pagination
        v-if="total > 0"
        :total="total"
        v-model:page="pageState.pageNum"
        v-model:limit="pageState.pageSize"
        @pagination="handleChangePage"
      />
    </el-card>
    <el-dialog
      v-model="addModal"
      title="新增-其他问题(随手拍)"
      width="46vw"
      destroy-on-close
      custom-class="add-check"
      @close="handleCancel"
    >
      <el-form
        :model="formData"
        label-width="180px"
        ref="formDataRef"
        :rules="formRules"
      >
        <el-form-item label="问题标题" prop="snapshotName">
          <el-input v-model="formData.snapshotName" maxlength="140"></el-input>
        </el-form-item>
        <el-form-item label="问题内容" prop="content">
          <el-input
            type="textarea"
            v-model="formData.content"
            :rows="3"
            maxlength="140"
          ></el-input>
        </el-form-item>
        <el-form-item label="随手拍照片" prop="snapshotAttachment">
          <ecm-image-upload
            :files="formData.snapshotAttachment"
            @set-file="
              fileList => {
                handleChange(fileList);
              }
            "
          ></ecm-image-upload>
        </el-form-item>
        <el-form-item label="项目执行组(专业组组长)" prop="partybHandlerInfo">
          <el-select
            v-model="formData.partybHandlerInfo"
            filterable
            clearable
            remote
            placeholder="请输入姓名搜索"
            :remote-method="getUserData"
            value-key="value"
            style="width: 100%"
          >
            <el-option
              v-for="item in userList"
              :key="item.value"
              :label="item.label"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSure" :loading="sureLoading"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 验收详情 -->
    <el-dialog
      v-model="showCheckDetail"
      title="查看-其他问题（随手拍）"
      width="52%"
      destroy-on-close
      custom-class="check-list check-color"
    >
      <check-detail
        @closeDetail="showCheckDetail = false"
        :instanceId="instanceId"
        module="snap"
      ></check-detail>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
// import { useRouter } from "vue-router";
import RePagination from "/@/components/RePagination/index.vue";
import { snapBatchStart, snapRecordList } from "/@/api/construction";
import { storageLocal } from "/@/utils/storage";
import { getUserList } from "/@/api/user";
import ecmImageUpload from "/@/components/ecmImage/index.vue";
import { onFilterFileData } from "/@/utils/file";
import { clickEvent } from "/@/utils/func";
import NotifMessage from "/@/utils/message/notification";
import checkDetail from "../components/checkDetail.vue";

const formRef = ref<HTMLFormElement | null>(null) as any;
let projectInfo = storageLocal.getItem("projectInfo");
let sectionInfo = storageLocal.getItem("sectionInfo");
const initData = {
  snapshotName: "",
  createTimeStrStart: "",
  createTimeStrEnd: ""
};

const formInline = reactive(initData);
const timeValue = ref(null);
const pageState = reactive({
  pageNum: 1,
  pageSize: 10
});
const tableData = ref([]);
const total = ref<number>(0);
const loading = ref<boolean>(false);
const sureLoading = ref<boolean>(false);
const formParams = ref<typeof initData>({ ...initData });

// 新增表单
const addModal = ref<boolean>(false);
const formDataRef = ref<HTMLFormElement | null>(null) as any;
const formData = reactive({
  snapshotName: "",
  content: "",
  snapshotAttachment: [] as any,
  partybHandlerInfo: "" as any,
  partybHandlerId: "",
  partybHandlerName: "",
  projectManageId: projectInfo?.id,
  projectName: projectInfo?.name,
  sectionId: sectionInfo?.id,
  monomerId: ""
});
const formRules = ref({
  snapshotName: [
    { required: true, message: "请填写问题标题", trigger: "change" }
  ],
  content: [{ required: true, message: "请填写问题内容", trigger: "change" }],
  snapshotAttachment: [
    { required: true, message: "请上传照片", trigger: "change" }
  ],
  partybHandlerInfo: [
    {
      required: true,
      message: "请选择项目执行组(专业组组长)",
      trigger: "change"
    }
  ]
});
const userList = ref([]); // 人员列表数据

// 详情弹窗
const showCheckDetail = ref<boolean>(false);
const instanceId = ref();

//获取数据列表
const getTableList = async (obj: object = {}) => {
  try {
    loading.value = true;
    const { code, data } = await snapRecordList({
      ...obj,
      sectionId: sectionInfo?.id,
      ...pageState
    });
    if (code === 200) {
      tableData.value = data.list;
      total.value = data.rows;
    }
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
};

//改变时间
const handleChangeDate = item => {
  if (item) {
    formInline.createTimeStrStart = item[0];
    formInline.createTimeStrEnd = item[1];
  } else {
    formInline.createTimeStrStart = "";
    formInline.createTimeStrEnd = "";
  }
};

const handleReset = () => {
  formRef.value.resetFields();
  timeValue.value = null;
  formParams.value = initData;
  handleChangeDate(null);
  getTableList(formInline);
};

const handleSearch = () => {
  pageState.pageNum = 1;
  formParams.value = formInline;
  getTableList(formInline);
};

const handleChangePage = () => {
  getTableList(formParams.value);
};

onMounted(() => {
  setTimeout(handleSearch, 0);
});

const handleAdd = () => {
  addModal.value = true;
};

// 获取项目组成员
const getUserData = async (query = "") => {
  if (!query) {
    userList.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: query
    };
    const { code, data } = await getUserList(params);
    if (code === 200) {
      userList.value = data.list.map(item => {
        return { value: item.id, label: `${item.name}(${item.userName})` };
      });
    }
  } catch (err) {
    console.log(err);
  }
};
// 文件上传
const handleChange = fileList => {
  formData.snapshotAttachment = fileList;
  formDataRef.value.clearValidate("snapshotAttachment");
};
// 确认新增-发起
const handleSure = async () => {
  sureLoading.value = true;
  const isValid = await formDataRef.value.validate();
  if (!isValid) return;
  const params = { ...formData };
  const fileList = formData.snapshotAttachment;
  params.partybHandlerId = params?.partybHandlerInfo?.value;
  params.partybHandlerName = params?.partybHandlerInfo?.label;
  params.snapshotAttachment = onFilterFileData(fileList);
  params.remark = JSON.stringify([
    { name: "问题标题", content: params.snapshotName, type: "input" },
    { name: "问题内容", content: params.content, type: "textarea" },
    {
      name: "随手拍照片",
      content: fileList,
      type: "images"
    }
  ]);
  try {
    const { code, message } = await snapBatchStart(params);
    if (code === 200) {
      addModal.value = false;
      formDataRef.value.resetFields();
      clickEvent("其它问题（随手拍）", "新增", "新增-其它问题（随手拍）");
      // 请求列表
      handleSearch();
      NotifMessage.success(message);
    } else {
      message && NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
  sureLoading.value = false;
};
// 取消
const handleCancel = () => {
  addModal.value = false;
  formDataRef.value.resetFields();
};
// 查看详情
const handleShowDetail = row => {
  showCheckDetail.value = true;
  instanceId.value = row.instanceId;
};
</script>

<style lang="scss" scoped>
:deep .back-picture {
  .el-upload-list__item {
    width: 56px;
    height: 56px;

    .el-upload-list__item-actions {
      font-size: 18px;
    }
  }

  .el-upload--picture-card {
    width: 56px;
    height: 56px;
    background: #fdfdff;
    border-radius: 4px;
    border: 1px solid #e4e8f2;

    i {
      height: 100%;
      width: 100%;
      line-height: 100%;
      font-size: 18px;
      color: #8c939d;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      span {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #8895b7;
      }
    }
  }
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

:deep .add-check {
  .el-dialog__body {
    padding: 20px 40px 8px 10px;
  }
}

.check-table {
  padding-left: 20px;

  .card-header {
    font-weight: bold;
    color: #494c53;
  }

  .el-table {
    width: 100%;
    margin: 20px 0;
  }
}
</style>
